const { TodoTableModel } = require('../db');
const TodoModel = require('../models/Todo');

class TodoController {
  constructor() {
    TodoController.funcBind(this);
    //传入数据库表，确保仅实例化一次，避免数据库多次创建新表
    this.todoModel = new TodoModel(TodoTableModel);
  }

  static funcBind(vm) {
    vm.getTodoList = vm.getTodoList.bind(vm);
    vm.getTodo = vm.getTodo.bind(vm);
    vm.addTodo = vm.addTodo.bind(vm);
    vm.toggleTodo = vm.toggleTodo.bind(vm);
    vm.removeTodo = vm.removeTodo.bind(vm);
  }

  async getTodoList(req, res) {
    const todoList = await this.todoModel.getTodoList();
    res.send({
      msg: 'Get todoList successfully!',
      code: 0,
      data: todoList
    });
  }

  async getTodo(req, res) {
    const id = req.body.id;
    const todo = await this.todoModel.getTodo(id);
    res.send({
      msg: 'Get todo successfully!',
      code: 0,
      data: todo
    });
  }

  //首页列表页面的新增todo路由处理函数
  async addTodo(req, res) {
    const todo = req.body;
    const result = await this.todoModel.addTodo(todo);
    res.send({
      msg: 'TodoItem add successfully!',
      code: 0,
      data: result
    });
  }

  //首页列表页面的修改todo路由处理函数
  async toggleTodo(req, res) {
    const { id } = req.body;
    const result = await this.todoModel.toggleTodo(id);
    res.send({
      msg: 'ToggleItem successfully!',
      code: 0,
      data: result
    });
  }

  //首页列表页面的移除todo路由处理函数
  async removeTodo(req, res) {
    const { id } = req.body;
    const result = await this.todoModel.removeTodo(id);
    res.send({
      msg: 'RemoveItem successfully!',
      code: 0,
      data: result
    });
  }
}

module.exports = TodoController;
